<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公告标题" prop="messageTitle">
        <el-input v-model="queryParams.messageTitle" placeholder="请输入公告标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="公告内容" prop="messageContext">
        <el-input v-model="queryParams.messageContext" placeholder="请输入公告内容" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="发布时间" style="width: 308px">
        <el-date-picker v-model="daterangeRelaseTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="公告状态" prop="messstatus">
        <el-select style="width: 100px;" v-model="queryParams.messstatus" placeholder="请选择公告状态" clearable>
          <el-option 
            v-for="dict in messTypes" 
            :key="dict.id" 
            :label="dict.type" 
            :value="dict.id" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="发布人" prop="relasePerson">
        <el-input v-model="queryParams.relasePerson" placeholder="请输入发布人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['sysmanagement:message:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['sysmanagement:message:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['sysmanagement:message:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['sysmanagement:message:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="messageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公告消息编号(排序号)" align="center" prop="id" />
      <el-table-column label="公告消息标题" align="center" prop="messageTitle" />
      <!-- <el-table-column label="公告消息内容" align="center" prop="messageContext" /> -->
      <el-table-column label="公告消息发布时间" align="center" prop="relaseTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.relaseTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="公告消息接收人" align="center" prop="recipient">
        <template #default="scope">
          <dict-tag :options="pay_type" :value="scope.row.recipient ? scope.row.recipient.split(',') : []" />
        </template>
      </el-table-column> -->
      <el-table-column label="公告消息状态" align="center" prop="messstatus">
        <template #default="scope">
         
           <span v-for="mt in messTypes" :key="mt">
            <span v-if="mt.id == scope.row.messstatus">
              {{ mt.type }}
            </span>
           </span>
        </template>
      </el-table-column>
      <el-table-column label="发布人" align="center" prop="relasePerson" />
      <el-table-column label="编辑时间" align="center" prop="editTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.editTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['sysmanagement:message:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['sysmanagement:message:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  
    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="messageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公告标题" prop="messageTitle">
          <el-input v-model="form.messageTitle" placeholder="请输入公告消息标题" />
        </el-form-item>
        <el-form-item label="公告内容" prop="messageContext">
          <el-input v-model="form.messageContext" placeholder="请输入公告消息内容" />
        </el-form-item>
        <!-- <el-form-item label="发布时间" prop="relaseTime">
          <el-date-picker clearable v-model="form.relaseTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择公告发布时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="接收人" prop="recipient">
          <el-button icon="Plus" primary plain @click="handleopeninner">
            添加接收人
          </el-button>

          <el-dialog v-model="centerDialogVisible" title="Warning" width="500" align-center>
            <span>Open the dialog from the center from the screen</span>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="centerDialogVisible = false">Cancel</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">
                  Confirm
                </el-button>
              </div>
            </template>
          </el-dialog>
          <!-- <el-checkbox-group v-model="form.recipient">
            <el-checkbox
              v-for="dict in doctors"
              :key="dict.id"
              :label="dict.name">
              {{dict.label}}
            </el-checkbox>
          </el-checkbox-group> -->
        </el-form-item>
        <!-- 接收人列表 内层 -->
        <el-dialog v-model="openinner" width="670" title="选择接收人" append-to-body>
          <el-table
            ref="multipleTableRef"
            :data="doctors"
            row-key="id"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column label="编号" width="120">
              <template #default="scope">{{ scope.row.id }}</template>
            </el-table-column>
            <!-- <el-table-column property="doctor.name" label="头像" width="120">
              <template #default="scope">{{ scope.row.avator }}</template>
            </el-table-column> -->
            <el-table-column label="头像" align="center" prop="avator" width="100">
              <template #default="scope">
                <image-preview :src="scope.row.avator" :width="50" :height="50"/>
              </template>
            </el-table-column>
            <el-table-column property="doctor.name" label="姓名" width="120" >
              <template #default="scope">{{ scope.row.name }}</template>
            </el-table-column>
            <el-table-column property="联系电话" label="联系电话" width="120" >
              <template #default="scope">{{ scope.row.tel }}</template>
            </el-table-column>
            <!-- <el-table-column property="角色" label="角色" width="120" >
              <template #default="scope">{{ scope.row.name }}</template>
            </el-table-column> -->
            <el-table-column property="所属团队" label="所属团队" width="120" >
              <template #default="{ row }">
                <span v-for="dt in docteams" :key="dt.id" >
                  <span v-if="dt.doctorId === row.id" >
                    {{ getTeamName(dt.teamId) }}
                  </span>
                </span>
              </template>
            </el-table-column>
            
          </el-table>
            <div style="text-align: right;">
              <el-button style="margin-top: 20px;" type="primary" @click="add_doc_message">添 加</el-button>
            </div>
        </el-dialog>
        <el-form-item label="公告状态" prop="messageType">
          <el-select style="width:100px;" v-model="form.messstatus" placeholder="请选择公告状态" clearable>
          <el-option
            v-for="dict in messTypes"
            :key="dict.id"
            :label="dict.type"
            :value="dict.id"
          />
        </el-select>
        </el-form-item>
        <!-- <el-form-item label="发布人" prop="relasePerson">
          <el-input v-model="form.relasePerson" placeholder="请输入发布人" />
        </el-form-item> -->
        <!-- <el-form-item label="编辑时间" prop="editTime">
          <el-date-picker clearable v-model="form.editTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择编辑时间">
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Message">
import { listMessage, getMessage, delMessage, addMessage, updateMessage } from "@/api/sysmanagement/message";
import { listDoctor } from "@/api/system/doctor";
import { listTeam } from "@/api/system/team";
import { listDoctorteam } from "@/api/sysmanagement/doctorteam";
import { ref } from "vue";
import { addDocmessage } from "@/api/sysmanagement/docmessage";
import { listMessagetype } from "@/api/sysmanagement/messagetype";
const { proxy } = getCurrentInstance();
const { pay_type, home_sys_notice_type } = proxy.useDict('pay_type', 'home_sys_notice_type');

const messageList = ref([]);
const open = ref(false);
const openinner = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeRelaseTime = ref([]);
const multipleTableRef = ref(null);
//定义一个公告类型数组存放状态集合
const messTypes = ref([])
//定义一个方法获取状态类型
function getMessagetype(){
  listMessagetype().then(response => {
    messTypes.value = response.rows;
    console.log(messTypes.value);
  });
}
//定义一个动态数组存放医生集合
const doctors = ref([])
//定义方法获取医生集合
function getdockers() {
  listDoctor().then(response => {
    doctors.value = response.rows;
  });
}
//定义一个动态数组存放医生对应团队集合
const docteams = ref([])
function getdocteam(){
  listDoctorteam().then(response => {
    docteams.value = response.rows;
  });
}
//定义一个动态数组存放团队集合
const team = ref([])
//获取医生团队集合
function getDoctorTeam(){
  listTeam().then(response => {
    team.value = response.rows;
  });
}
//定义一个方法通过teamId查询teamName
function getTeamName(teamId){
  const team = this.team.find(team => team.id === teamId);
  return team ? team.name : '未知团队';
}
// 控制行是否可选
function selectable(row, index) {
  return true;
}
function add_doc_message() {
  if (!multipleTableRef.value) {
    proxy.$modal.msgWarning('表格引用未初始化');
    return;
  }
  
  const selectedDoctors = multipleTableRef.value.getSelectionRows();
  if (selectedDoctors.length === 0) {
    proxy.$modal.msgWarning('请选择要推送的医生');
    return;
  }
  
  // 仅关闭内层对话框，不执行保存操作
  openinner.value = false;
}
// 使用 onMounted 确保 $refs 已经初始化
onMounted(() => {
  console.log(proxy.$refs.multipleTableRef); // 检查是否正确获取到 el-table 实例
});
// 监听 openinner 的变化，确保 $refs 可用
watch(openinner, (newValue) => {
  if (newValue) {
    // 使用 nextTick 确保在 DOM 更新后获取 $refs
    nextTick(() => {
      console.log(proxy.$refs.multipleTableRef.selection);
    });
  }
});
//嵌套dialog
const outerVisible = ref(false)
const innerVisible = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    messageTitle: null,
    messageContext: null,
    relaseTime: null,
    relasePerson: null,
    messstatus:null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询公告列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeRelaseTime && '' != daterangeRelaseTime) {
    queryParams.value.params["beginRelaseTime"] = daterangeRelaseTime.value[0];
    queryParams.value.params["endRelaseTime"] = daterangeRelaseTime.value[1];
  }
  listMessage(queryParams.value).then(response => {
    // console.log('公告列表数据:', response.rows);
    messageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    messageTitle: null,
    messageContext: null,
    relaseTime: null,
    // recipient: [],
    messageType: null,
    relasePerson: null,
    editTime: null,
    messstatus:null,
    exp2: null
  };
  proxy.resetForm("messageRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeRelaseTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// test新增outer
function handleAddouter(){
  reset();
  outerVisible.value = true;
  title.value = "添加公告";
}
// test新增inner
function handleAddinner(){
  reset();
  innerVisible.value = true;
}
/** 打开接收人 */
function handleopeninner(){
  openinner.value = true;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加公告";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getMessage(_id).then(response => {
    form.value = response.data;
    // form.value.recipient = form.value.recipient.split(",");
    open.value = true;
    title.value = "修改公告";
  });
}

/** 提交按钮 */
// function submitForm() {
//   proxy.$refs["messageRef"].validate(valid => {
//     if (valid) {
//       form.value.recipient = form.value.recipient.join(",");
//       if (form.value.id != null) {
//         updateMessage(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功");
//           open.value = false;
//           getList();
//         });
//       } else {
//         addMessage(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功");
//           open.value = false;
//           getList();
//         });
//       }
//     }
//   });
// }
function submitForm() {
  proxy.$refs["messageRef"].validate(valid => {
    if (valid) {
      const selectedDoctors = multipleTableRef.value?.getSelectionRows() || [];
      const doctorIds = selectedDoctors.map(d => d?.id).filter(id => id);
      if (form.value.id) {
       // 修改操作
       updateMessage(form.value).then(response => {
          const messageId = form.value.id;
          const savePromises = doctorIds.map(doctorid => {
            return addDocmessage({
              doctorid: doctorid,
              messageid: messageId,
              exp2: null
            });
          });
          Promise.all(savePromises).then(() => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        });
      }else{
      // 先保存公告数据
      addMessage(form.value).then(response => {
        const messageId = response.data;
        
        // 创建保存关联关系的Promise数组
        const savePromises = doctorIds.map(doctorid => {
          return addDocmessage({
            doctorid: doctorid,
            messageid: messageId,
            relasetime: null,
            exp2: null
          });
        });
        
        // 等待所有关联关系保存完成
        return Promise.all(savePromises);
      })
      .then(() => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
    }
  });
}
// function submitForm() {
//   proxy.$refs["messageRef"].validate(valid => {
//     if (valid) {
//       let message_id = '';
//       // 获取选中的医生列表
//       const selectedDoctors = multipleTableRef.value?.getSelectionRows() || [];
//       console.log(selectedDoctors);
//       const doctorIds = selectedDoctors.map(d => d?.id).filter(id => id); // 确保所有ID有效
//       console.log(doctorIds);
//       // 设置接收人信息
//       form.value.recipient = doctorIds.join(',');
      
//       // addMessage(form.value).then(response => {
//       //   const messageId = response.data;
//       //   // 为每个医生ID创建关联关系
//       //   doctorIds.forEach(doctorId => {
//       //     addDocmessage({
//       //       doctorId: doctorId,
//       //       messageId: messageId,
//       //       exp1: null,
//       //       exp2: null
//       //     });
//       //   });
//       //   proxy.$modal.msgSuccess("新增成功");
//       //   open.value = false;
//       //   getList();
//       // });
//       // 保存公告数据
//       addMessage(form.value).then(response => {
//           console.log("aaaaaaa",response);
//           message_id = response.data
//           proxy.$modal.msgSuccess("新增成功");
//         });
//       function add_doc_message(){
//         doctorIds.forEach(doctorid => {
//             console.log(doctorid);
//             addDocmessage({
//             doctorid: doctorid,
//             messageid: message_id,
//             exp1: null,
//             exp2: null
//           });
//         });
//       }
//       add_doc_message()
//       // 保存关联关系

//       // addDocmessage({
//       //       doctorId: doctorId,
//       //       messageId: message_id,
//       //       exp1: null,
//       //       exp2: null
//       //     });
     
//     }
//   });
// }

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除公告编号为"' + _ids + '"的数据项？').then(function () {
    return delMessage(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sysmanagement/message/export', {
    ...queryParams.value
  }, `message_${new Date().getTime()}.xlsx`)
}

getList();
getdockers();
getDoctorTeam();
getdocteam();
getMessagetype()
</script>
